package com.itlaobing.web.management.controller;

import com.itlaobing.pojo.SystemUser;
import com.itlaobing.service.SystemUserService;
import com.itlaobing.util.GraphicHelper;
import com.itlaobing.util.StringHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.swing.text.html.parser.Entity;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("management")
public class ManagementHomeController {
    @Autowired
    SystemUserService systemUserService;
    //上下文路径
    @Autowired
    private ServletContext application;
    private Log log=LogFactory.getLog(ManagementHomeController.class);
    /**
     * 生成图片验证码方法
     * @param session
     * @return
     */
    @RequestMapping("code")
    public ResponseEntity<byte[]> identify(HttpSession session ) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String code = GraphicHelper.create( 4 , false , 180 , 50 , baos , 50 );
        // 需要修改session  的键
        session.setAttribute("loginCode",code);

        byte[] body = baos.toByteArray()  ;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType( MediaType.IMAGE_JPEG );

        ResponseEntity<byte[]> re = new ResponseEntity<>( body , headers , HttpStatus.OK );

        return re ;
    }
    /**
     * 打开登陆页面
     * @return
     */
    @RequestMapping(path = "/page/signin",method = RequestMethod.GET)
    public String  signinPage(){
        return "/management/signin";
    }

    /**
     * 登陆成功
     * @param account
     * @param password
     * @param code
     * @param model
     * @return
     */
    @RequestMapping(path = "/action/signin",method = RequestMethod.POST)
    public String signinAction(String account,String password,String code,Model model,HttpSession session ){
        log.info(">>>>>>>>>"+account+","+password+","+code);
        //数据校验
        if(StringHelper.empty(account)){
            //数据回显
            model.addAttribute("account",account);
            model.addAttribute("password",password);
            model.addAttribute("error","请输入您的账号");
            return "/management/signin";
        }
        if(StringHelper.empty(password)){
            model.addAttribute("account",account);
            model.addAttribute("password",password);
            model.addAttribute("error","请输入您的密码");
            return "/management/signin";
        }
        if(StringHelper.empty(code)){
            model.addAttribute("account",account);
            model.addAttribute("password",password);
            model.addAttribute("error","请输入验证码");
            return "/management/signin";
        }
        //获取session中的验证码
        String sessioncode=session.getAttribute("loginCode").toString();
        if(!StringHelper.equals(code,sessioncode,true,true)){
            model.addAttribute("account",account);
            model.addAttribute("password",password);
            model.addAttribute("error","输入验证码不正确");
            return "/management/signin";
        }
        //数据封装
        SystemUser user=new SystemUser();
        user.setSystemuseraccount(account);
        user.setSystemuserpassword(password);
        //业务调用
        SystemUser systemUser=systemUserService.findBySystemUser(user);
        //若登陆成功，则重定向到home页面
        if(systemUser==null){
            model.addAttribute("account",account);
            model.addAttribute("password",password);
            model.addAttribute("error","输入账号或密码不正确");
            return "/management/signin";
        }
        //通过id和状态来查询
        systemUser.setSystemuserstatus(0l);
        SystemUser systemUser1=systemUserService.findByIdAndStatus(systemUser);
        if(systemUser1==null){
            model.addAttribute("account",account);
            model.addAttribute("password",password);
            model.addAttribute("error","您的账号已经被锁定");
            return "/management/signin";
        }
        session.setAttribute("loginuser",systemUser1);
        //将此时的时间登陆下来
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("id",systemUser1.getSystemuserid());
        map.put("logintime",new Date());
        //调用业务，将登陆时间更新
        systemUserService.updateLoginTimeById(map);
        return "redirect:/management/page/home";
    }

    //成功后打开主页面
    @RequestMapping(path="/page/home",method = RequestMethod.GET)
    public String homePage(){
        return "/management/user/home";
    }

    /**
     * ajax通过账号验证
     * @param account
     * @return
     */
    @RequestMapping(path = "/action/checkAccount",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> checkAccount(String account){
        Map<String,Object> map=new HashMap<String,Object>();
        //调用业务层
        Boolean rs=systemUserService.findByAccount(account);
        if(rs){
            map.put("result",true);
        }else{
            map.put("result",false);
        }
        return map;
    }

    /**
     * 退出登陆
     * @return
     */
    @RequestMapping(path = "/action/signout")
    public String signout(HttpSession session){
        session.invalidate();
        return "redirect:/management/page/signin";
    }
    /**
     * 跳转到修改密码的页面
     */
    @RequestMapping(path = "page/updatepass",method = RequestMethod.GET)
    public String updatePass(){
         return "/management/user/updatepass";
    }
    /**
     * 修改密码操作
     */
    @RequestMapping(path = "/action/updatepass",method = RequestMethod.POST)
    public String updatePassAction(String password,String newpass,String resetpass,Model model,HttpSession session){
        //获取session
        SystemUser user=(SystemUser) session.getAttribute("loginuser");
        //数据校验
        if(StringHelper.empty(password)){
            //数据回显
            model.addAttribute("password",password);
            model.addAttribute("newpass",newpass);
            model.addAttribute("resetpass",resetpass);
            model.addAttribute("error","请输入密码");
            return "/management/user/updatepass";
        }
        //从session中获取原来的面貌
        if (!StringHelper.equals(password,user.getSystemuserpassword(),true,false)){
            //数据回显
            model.addAttribute("password",password);
            model.addAttribute("newpass",newpass);
            model.addAttribute("resetpass",resetpass);
            model.addAttribute("error","原密码不正确");
            return "/management/user/updatepass";
        }
        if(StringHelper.empty(newpass)){
            //数据回显
            model.addAttribute("password",password);
            model.addAttribute("newpass",newpass);
            model.addAttribute("resetpass",resetpass);
            model.addAttribute("error","请输入新密码");
            return "/management/user/updatepass";
        }
        if(StringHelper.equals(newpass,password,true,false)){
            //数据回显
            model.addAttribute("password",password);
            model.addAttribute("newpass",newpass);
            model.addAttribute("resetpass",resetpass);
            model.addAttribute("error","新密码不能与原密码一致");
            return "/management/user/updatepass";
        }
        if(!StringHelper.equals(resetpass,newpass,true,false)){
            //数据回显
            model.addAttribute("password",password);
            model.addAttribute("newpass",newpass);
            model.addAttribute("resetpass",resetpass);
            model.addAttribute("error","两次输入的密码不一致");
            return "/management/user/updatepass";
        }
        //数据封装
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("id",user.getSystemuserid());
        map.put("pass",newpass);
        //调用业务层
        Boolean  rs=systemUserService.updatePassById(map);
        if (rs){
            //密码修改成功，替换session中的原密码
            user.setSystemuserpassword(newpass);
            session.setAttribute("loginuser",user);
            model.addAttribute("success","密码修改成功");
        }else{
            model.addAttribute("defeat","服务器异常");
        }
        return  "/management/user/updatepass";
    }
    /**
     * 打开上传图片界面
     * @return
     */
    @RequestMapping(path = "/page/headimage",method = RequestMethod.GET)
    public String uploadHeadimagePage(){
        return "/management/user/headimage";
    }

    /**
     * 上传图片  将图片复制到指定的目录，并将图片地址封装到map集合中
     * @return
     */
    @RequestMapping(path = "/action/upload",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> uploadimage(@RequestParam("file") MultipartFile file){
        Map<String,String> map = new HashMap<String,String>();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMM");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        //指定文件保存路径
        String path =  application.getRealPath("/assets/upload/imgs");


        date.setTime(System.currentTimeMillis());
        String name = sdf1.format(date);

        //根据日期创建文件夹
        Path target = Paths.get(path,name);

        //判断目录是否存在，如不存在，则创建出来
        if(Files.notExists(target)){
            try {
                Files.createDirectories(target);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //获取文件名，并修修改文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件扩展名
        String suffix =  originalFilename.substring(originalFilename.lastIndexOf("."));
        //将毫秒数作为新的文件名
        date.setTime(System.currentTimeMillis());
        String filename = sdf2.format(date)+suffix;
        //将文件复制到指定路径
        try {
            file.transferTo(new File(target.toString(),filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将文件地址返回给页面
        map.put("result","/assets/upload/imgs/"+name+"/"+filename);

        return  map;
    }

    /**
     * 保存头像地址到数据库
     * @return
     */
    @RequestMapping(path = "/action/saveheadimage",method = RequestMethod.POST)
    public String saveHeadImage(String userid,String systemuserimage,Model model,HttpSession session){

        //数据封装
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",userid);
        map.put("image",systemuserimage);

        //业务调用，将图片地址保存到数据库
        boolean rs = systemUserService.UpdateHeadImageById(map);

        //结果判断
        if(rs){
            SystemUser systemUser = (SystemUser)session.getAttribute("loginuser");
            systemUser.setSystemuserimage(systemuserimage);
            session.setAttribute("loginuser",systemUser);
            return "redirect:/management/page/home";
        }else{
            model.addAttribute("error","服务器异常");
            return "/management/user/headimage";
        }

    }
}
